<?php
/***************************************************************************
 *
 *   copyright            : (C) 2005 Winds of Storm
 *
 *   $Id: index.php,v 1.8 2006/03/10 23:12:03 nathan Exp $
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

require("../config.php");
$skip_header    = 1;
require($libdir . "init." . $phpEx);
require($libdir . "chat_functs." . $phpEx);
require($libdir . "admin." . $phpEx);
require($libdir . "rooms." . $phpEx);

$timeout_help   = array(
    'TIME_NOPULL'   => 'For client pull and slimchat, the amount of time since the user has polled for updates. If they have not polled in X seconds, time them out (usually the browser window has been closed without logging out).',
    'TIME_IDLE'     => 'The amount of time before a user is flagged as being idle (notice sent to room).',
    'TIME_LIMBO'    => 'The amount of time before a user is flagged as being in limbo (notice sent to room).',
    'TIME_WARN'     => 'The amount of time before a user is warned that they are going to be timed out. This should not apply to moderators and admins.',
    'TIME_TIMEOUT'  => 'The amount of time before a user is disconnected for being idle too long. This should not apply to moderators and admins.',
);

$setting_help   = array(
    'CHAT_SERVER'           => 'The hostname used for server push. This can be left blank if you do not use the binary server.',
    'CHAT_PORT'             => 'The port used for server push. This can be left blank if you do not use the binary server.',
    'CHAT_URL'              => 'The URL to access chat.',
    'DEFAULT_ROOM'          => 'The room ID which will be selected by default. You can find this by checking the Manage Rooms page.',
    'FORUM_BASE_URL'        => 'The base URL for your forums.',
    'FORUM_DB_PREFIX'       => 'The database prefix used by your forum installation.',
    'FORUM_LINK_URL'        => 'The URL for the link to your forums displayed in chat. You can point this to a specific board or post, customize it how you wish. It is purely cosmetic.',
    'FORUM_NAME'            => 'The name on the link to your forums displayed in chat.',
    'FORUM_SMILIES_PATH'    => 'If you use a custom set of smilies, specify the path to them here.',
    'FORUM_TYPE'            => 'Which Forum Access Layer (FAL) you use. Be very careful changing this.',
);

$cron_helper    = array(
    array('name'    => '1 minute',      'interval'  => 1,   'syntax'    => '*',    'time'      => 60),
    array('name'    => '2 minutes',     'interval'  => 2,   'syntax'    => '*/2',  'time'      => 120),
    array('name'    => '5 minutes',     'interval'  => 5,   'syntax'    => '*/5',  'time'      => 300),
    array('name'    => '10 minutes',    'interval'  => 10,  'syntax'    => '*/10', 'time'      => 600),
    array('name'    => '15 minutes',    'interval'  => 15,  'syntax'    => '*/15', 'time'      => 900),
);

$op = strtolower($_REQUEST['op']);

$template   = new Template($config['TPL_DIR']);
if ($op == '') {
    $sql                = "SELECT COUNT(*) AS config_count FROM {$dbprefix}config";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['config']    = $row['config_count'];
    
    $sql                = "SELECT COUNT(user_id) AS prefs_count FROM {$dbprefix}prefs";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['prefs']     = $row['prefs_count'];
    
    $sql                = "SELECT COUNT(room_id) AS room_count FROM {$dbprefix}rooms";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['rooms']     = $row['room_count'];
    
    $sql                = "SELECT COUNT(event_id) AS event_count FROM {$dbprefix}events";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['events']    = $row['event_count'];
    
    $sql                = "SELECT COUNT(alias_id) AS alias_count FROM {$dbprefix}aliases";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['aliases']   = $row['alias_count'];
    
    $sql                = "SELECT COUNT(session_id) AS session_count FROM {$dbprefix}sessions";
    $res                = $db->sql_query($sql);
    $row                = $db->sql_fetchrow($res);
    $stats['sessions']  = $row['session_count'];
    
    foreach ($stats as $stat => $stat_value) {
        $stat_name  = ucfirst($stat);
    
        print("$stat_name table has $stat_value entries<br />");
    }
} else if (($op == 'manage_rooms') || ($op == 'del_room') || ($op == 'new_room')) {
    if ($op == 'del_room') {
        $sql    = "SELECT * FROM {$dbprefix}rooms WHERE room_id={$_REQUEST['rid']}";
        $res    = $db->sql_query($sql);
        $row    = $db->sql_fetchrow($res);
    
        $sql    = "DELETE FROM {$dbprefix}events WHERE room_id_to={$_REQUEST['rid']}";
        $res    = $db->sql_query($sql);
        $events = $db->sql_numrows($res);
        if ($events == '') {
            $events = 0;
        }

        $sql    = "DELETE FROM {$dbprefix}rooms WHERE room_id={$_REQUEST['rid']}";
        $res    = $db->sql_query($sql);
    
        $notice = "Deleted <b>" . $row['room_name'] . "</b> ($events events purged).";
    } else if ($op == 'new_room') {
        if ($_REQUEST['room_name'] != '') {
            $sql    = "INSERT INTO {$dbprefix}rooms (room_name, room_group) VALUES ('{$_REQUEST['room_name']}', {$_REQUEST['gid']})";
            $res    = $db->sql_query($sql);
    
            $notice = "Added new room '{$_REQUEST['room_name']}'.";
        } else {
            $notice = "<b>ERROR:</b> Room name may not be empty.";
        }
    }

    $template->set_filenames(array('body' => 'admin/rooms_body.tpl'));
    $template->assign_vars(array(
        'U_INDEX'   => "index.$phpEx",
    ));
    
    if ($notice != '') {
        $template->assign_block_vars('switch_notice', array('NOTICE' => $notice));
    }

    $sql    = "SELECT * FROM {$dbprefix}room_groups ORDER BY group_id";
    $res    = $db->sql_query($sql);
    while ($row = $db->sql_fetchrow($res)) {
        $vars   = array();
        while (list($k, $v) = each($row)) {
            $vars[strtoupper($k)]   = $v;
        }
        $template->assign_block_vars('groups', $vars);

        $sql    = "SELECT *
                FROM
                    {$dbprefix}rooms 
                WHERE
                    room_group={$row['group_id']}
                ORDER BY
                    room_name";
        $res2   = $db->sql_query($sql);
    
        while ($row2 = $db->sql_fetchrow($res2)) {
            $vars   = array();
            while (list($k, $v) = each($row2)) {
                $vars[strtoupper($k)]   = $v;
            }
            if ($row2['room_password'] != '') {
                $vars['PROTECTED']  = " [protected]";
            }
            if ($row2['room_limit'] != '0') {
                $vars['LIMITED']    = " [limit: {$row2['room_limit']}]";
            }
            $template->assign_block_vars('groups.rooms', $vars);
        }
    }
    $template->pparse('body');
} else if (($op == 'manage_groups') || ($op == 'dynamic_group') || ($op == 'new_group') || ($op == 'del_group')) {
    if ($op == 'dynamic_group') {
        $sql    = "UPDATE {$dbprefix}room_groups SET group_dynamic='no' WHERE group_id={$_REQUEST['old_group_id']}";
        $res    = $db->sql_query($sql);
        $sql    = "UPDATE {$dbprefix}room_groups SET group_dynamic='yes' WHERE group_id={$_REQUEST['group_id']}";
        $res    = $db->sql_query($sql);
        $notice = "Updated the dynamic group.";
    } else if ($op == 'new_group') {
        if ($_REQUEST['group_name'] != '') {
            $sql    = "INSERT INTO {$dbprefix}room_groups (group_name) VALUES ('{$_REQUEST['group_name']}')";
            $res    = $db->sql_query($sql);
            $notice = "Added group '{$_REQUEST['group_name']}'.";
        } else {
            $notice = "<b>ERROR:</b> Group name may not be empty.";
        }
    } else if ($op == 'del_group') {
        $sql    = "SELECT * FROM {$dbprefix}room_groups WHERE group_id={$_REQUEST['gid']}";
        $res    = $db->sql_query($sql);
        $row    = $db->sql_fetchrow($res);
        $sql    = "DELETE FROM {$dbprefix}room_groups WHERE group_id={$_REQUEST['gid']}";
        $res    = $db->sql_query($sql);
        $notice = "Removed group '{$row['group_name']}'.";
    }

    $template->set_filenames(array('body' => 'admin/groups_body.tpl'));
    $template->assign_vars(array(
        'U_INDEX'   => "index.$phpEx"
    ));

    if ($notice != '') {
        $template->assign_block_vars('switch_notice', array('NOTICE' => $notice));
    }

    $sql    = "SELECT * FROM {$dbprefix}room_groups ORDER BY group_id";
    $res    = $db->sql_query($sql);

    while ($row = $db->sql_fetchrow($res)) {
        $vars   = array();
        while (list($k, $v) = each($row)) {
            $vars[strtoupper($k)]   = $v;
        }
        if ($row['group_dynamic'] == 'yes') {
            $old_gid        = $row['group_id'];
            $vars['CHECKED']    = ' CHECKED';
        }
        $template->assign_block_vars('groups', $vars);
    }
    $template->assign_vars(array(
        'OLD_GROUP_ID'  => $old_gid
    ));
    $template->pparse('body');
} else if ($op == 'edit_room') {
    $sql    = "SELECT * FROM {$dbprefix}rooms WHERE room_id={$_REQUEST['rid']}";
    $res    = $db->sql_query($sql);
    $row    = $db->sql_fetchrow($res);
    
    $template->set_filenames(array('body' => 'admin/room_edit.tpl'));
    $template->assign_vars(array(
        'ACTION'            => "index.$phpEx",
        'ROOM_ID'           => $_REQUEST['rid'],
        'ROOM_NAME'         => $row['room_name'],
        'ROOM_LIMIT'        => $row['room_limit'],
        'ROOM_PASSWORD'     => $row['room_password'],
        'ROOM_TOPIC'        => $row['room_topic'],
        'MODERATOR_GROUPS'  => showModeratorGroups($row['mod_group'])
    ));
    $template->pparse('body');
} else if ($op == 'update_room') {

    $sql    = "UPDATE {$dbprefix}rooms
            SET
                room_name='{$_REQUEST['room_name']}',
                room_limit='{$_REQUEST['room_limit']}',
                room_password='{$_REQUEST['room_password']}',
                room_topic='{$_REQUEST['room_topic']}',
                mod_group='{$_REQUEST['mod_group']}'
            WHERE
                room_id={$_REQUEST['rid']}";
    $res    = $db->sql_query($sql);
    print("Updated {$_REQUEST['room_name']}.");
} else if ($op == 'config_plugins') {
    $template->set_filenames(array('body' => 'admin/config_plugins.tpl'));
    foreach ($plugins as $plugin) {
        if ($config[$plugin['FUNC']] == 'enabled') {
            $enabled_y  = 'CHECKED ';
            $enabled_n  = '';
        } else {
            $enabled_y  = '';
            $enabled_n  = 'CHECKED ';
        }
        $template->assign_block_vars('plugin', array(
            'NAME'          => $plugin['NAME'],
            'AUTHOR'        => $plugin['CREDIT'],
            'ID'            => $plugin['FUNC'],
            'VERSION'       => $plugin['VERSION'],
            'ENABLED_TRUE'  => $enabled_y,
            'ENABLED_FALSE' => $enabled_n,
        ));
    }
    $template->pparse('body');
} else if ($op == 'update_plugins') {
    foreach ($plugins as $plugin) {
        $func   = $plugin['FUNC'];
        if ($config[$func] != $_REQUEST[$func]) {
            $sql    = "UPDATE {$dbprefix}config SET config_value='{$_REQUEST[$func]}' WHERE config_name='$func'";
            $res    = $db2->sql_query($sql);
            print ucfirst($_REQUEST[$func])." plugin $func.<br />\n";
        }
    }
} else if ($op == 'config_timeouts') {
    $template->set_filenames(array('body' => 'admin/config_timeouts.tpl'));
    foreach ($timeout_help as $key => $value) {
        $template->assign_block_vars('timeout', array(
            'NAME'  => $key,
            'HELP'  => $value,
            'VALUE' => $config[$key],
        ));
    }
    $template->pparse('body');
} else if ($op == 'update_timeouts') {
    $changed    = false;
    foreach ($timeout_help as $key => $value) {
        if ($_REQUEST[$key] != $config[$key]) {
            $sql    = "UPDATE {$dbprefix}config SET config_value={$_REQUEST[$key]} WHERE config_name='$key'";
            $res    = $db2->sql_query($sql);
            print "Changing value of $key from {$config[$key]} to {$_REQUEST[$key]}.<br />\n";
            $changed    = true;
        }
    }
    if (!$changed) {
        print("No changes made.");
    }
} else if ($op == 'config_settings') {
    $template->set_filenames(array('body' => 'admin/config_settings.tpl'));
    foreach ($setting_help as $key => $value) {
        $template->assign_block_vars('setting', array(
            'NAME'  => $key,
            'HELP'  => $value,
            'VALUE' => $config[$key],
        ));
    }
    $template->pparse('body');
} else if ($op == 'update_settings') {
    $changed    = false;
    foreach ($setting_help as $key => $value) {
        if ($_REQUEST[$key] != $config[$key]) {
            if ($_REQUEST[$key] != '') {
                if (isset($config[$key])) {
                    $sql    = "UPDATE {$dbprefix}config SET config_value={$_REQUEST[$key]} WHERE config_name='$key'";
                    $res    = $db2->sql_query($sql);
                } else {
                    $sql    = "INSERT INTO {$dbprefix}config (config_name, config_value) VALUES ('$key', '{$_REQUEST[$key]}')";
                    $res    = $db2->sql_query($sql);
                }
                print "Changing value of $key from {$config[$key]} to {$_REQUEST[$key]}.<br />\n";
                $changed    = true;
            } else {
                if (isset($config[$key])) {
                    $sql    = "DELETE FROM {$dbprefix}config WHERE config_name='$key'";
                    $res    = $db2->sql_query($sql);
                }
                print "Removing $key from configuration (previous value: {$config[$key]}).<br />\n";
                $changed    = true;
            }
        }
    }
    if (!$changed) {
        print("No changes made.");
    }
} else if ($op == 'config_announce') {
    $template->set_filenames(array('body' => 'admin/config_announce.tpl'));
    $template->assign_vars(array(
        'ANNOUNCEMENT' => $config['ANNOUNCEMENT'],
    ));
    $template->pparse('body');
} else if ($op == 'update_announce') {
    $changed    = false;
    if ($_REQUEST['announcement'] != $config['ANNOUNCEMENT']) {
        if ($_REQUEST['announcement'] != '') {
            if (isset($config['ANNOUNCEMENT'])) {
                $sql    = "UPDATE {$dbprefix}config SET config_value='{$_REQUEST['announcement']}' WHERE config_name='ANNOUNCEMENT'";
                $res    = $db2->sql_query($sql);
            } else {
                $sql    = "INSERT INTO {$dbprefix}config (config_name, config_value) VALUES ('ANNOUNCEMENT', '{$_REQUEST['announcement']}')";
                $res    = $db2->sql_query($sql);
            }
            print "Changing value of 'ANNOUNCEMENT' from {$config['ANNOUNCEMENT']} to {$_REQUEST['announcement']}.<br />\n";
            $changed    = true;
        } else {
            if (isset($config['ANNOUNCEMENT'])) {
                $sql    = "DELETE FROM {$dbprefix}config WHERE config_name='ANNOUNCEMENT'";
                $res    = $db2->sql_query($sql);
            }
            print "Removing 'ANNOUNCEMENT' from configuration (previous value: {$config['ANNOUNCEMENT']}).<br />\n";
            $changed    = true;
        }
    }
    if (!$changed) {
        print("No changes made.");
    }
} else if ($op == 'config_cron') {
    $template->set_filenames(array('body' => 'admin/config_cron.tpl'));
    foreach ($cron_helper as $cron) {
        $vars   = array();
        foreach ($cron as $key => $value) {
            $vars[strtoupper($key)] = $value;
        }

        if ($cron['interval'] == $config['CRON_MINUTE_INTERVAL']) {
            $vars['SELECTED']   = 'SELECTED';
        }
        $template->assign_block_vars('cron', $vars);
    }
    $template->pparse('body');
} else if ($op == 'update_cron') {
    foreach ($cron_helper as $values) {
        if ($values['time'] == $_REQUEST['cron']) {
            $cron   = $values;
        }
    }
    if (!isset($cron)) {
        print("Error setting cron values.");
    } else {
        if (isset($config['CRON_MINUTE_INTERVAL'])) {
            $sql    = "UPDATE {$dbprefix}config SET config_value=".$cron['interval']." WHERE config_name='CRON_MINUTE_INTERVAL'";
        } else {
            $sql    = "INSERT INTO {$dbprefix}config (config_name, config_value) VALUES ('CRON_MINUTE_INTERVAL', {$cron['interval']})";
        }
        $res    = $db2->sql_query($sql);
        print("Set CRON_MINUTE_INTERVAL to {$cron['name']}. You should adjust your crontab to include the following:\n<pre>");
        $path   = $basedir.'scripts';
        print("{$cron['syntax']} * * * * $path/sessions.php\n");
        print("{$cron['syntax']} * * * * $path/timers.php\n");
        print("</pre>");
    }
} else {
    print("Unknown operation '$op'.<br /><pre>");
    print_r($_REQUEST);
    print("</pre>");
}

print("</td></tr>");
print("</table>");
?>
